package com.tfkj.contrller;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.tfkj.Config;
import com.tfkj.entity.Test;
import com.tfkj.service.AllService;
import com.tfkj.service.PDFParserUtil;
import com.tfkj.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.tfkj.Config.*;
import static com.tfkj.Config.url;
import static com.tfkj.contrller.PdfUtil.cutPDFPage;

@RestController
@CrossOrigin(maxAge = 3600)
@RequestMapping("/test")
@Api(value = "测验", tags = "测验接口")
public class TestController {

    @Autowired
    private AllService allService;
    @Autowired
    private Config config;

    @ApiOperation("查询测验列表（全量）")
    @PostMapping("/list")
    public CommonReturn getTests(@RequestParam(value = "name", required = false) String name, @RequestParam("pageNum")Integer pageNum, @RequestParam("pageSize")Integer pageSize) {
        List<Test> tests = allService.getTests(name, pageNum, pageSize);
        Integer total = allService.getTestsTotal(name);
        return new CommonReturn(tests,total);
    }


    @ApiOperation("修改测验名称")
    @PostMapping("/update")
    public CommonReturn updateTest(@RequestBody Test test) {
        allService.updateTest(test.getId(), test.getName(), test.getGrade(), test.getSubject());
        return new CommonReturn(200, "修改测验名称成功！");

    }
    @ApiOperation("修改测验Urls")
    @PostMapping("/updateUrls")
    public CommonReturn updateTest(@RequestBody UpdateTestUrlsVO vo) {
        allService.updateTestUrls(vo.getTestId(), vo.getUrls());
        return new CommonReturn(200, "修改测验名称成功！");
    }
    @ApiOperation("删除测验")
    @PostMapping("/delete/{id}")
    public CommonReturn updateTest(@PathVariable("id") Integer id) {
        allService.deleteTest(id);
        return new CommonReturn(200, "删除测验成功！");
    }

    @ApiOperation("上传测验试卷pdf并处理")
    @PostMapping("/create")
    public CommonReturn handleFileUpload(@RequestParam("file") MultipartFile file,
                                         @RequestParam("name") String name,
                                         @RequestParam("grade") String grade,
                                         @RequestParam("subject") String subject,
                                         @RequestParam(value = "type",required = false) String type,
                                         @RequestParam(value = "testNum",required = false) String testNum) {
        if (file.isEmpty()) {
            return new CommonReturn(500, "空文件");
        }
        String url = Config.url;
        try {
            System.out.println("文件:"+file.getOriginalFilename());

            int index = 1;
            List<String> urls = new ArrayList<>();
            for (InputStreamDTO image : cutPDFPage(file)) {
                try {
                    String key = new Date().getTime() +"_"+index+".png";
                    System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
                    AmazonS3 s3 = config.amazonS3();
                    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentType("image/png");
                    objectMetadata.setContentLength(image.getLength());
                    urls.add(url + key);
                    s3.putObject(bucket, key, image.getInputStream(), objectMetadata);
                    System.out.format("Uploading %s to S3 bucket %s...\n", key, bucket);
                } catch (AmazonServiceException e) {
                    System.err.println(e.getErrorMessage());
                    System.exit(1);
                }
                index++;
            }
            allService.createTest(name, grade, subject,String.join(",", urls), type, testNum);
            return new CommonReturn(200, "上传成功！");

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new CommonReturn(500, "上传失败！");
        }
    }

        @PostMapping("/createAndMakeImage")
        public CommonReturn parsePDF(
            @RequestParam("file") MultipartFile file,
            @RequestParam("name") String name, @RequestParam("grade") String grade, @RequestParam("subject") String subject
        ) {
            double offset = 1D;
            if (file.isEmpty()) {
                return new CommonReturn(500, "空文件");
            }
            String url = Config.url;
        try (InputStream is = file.getInputStream()) {
            Integer testId = allService.findMaxTestId();
            allService.insertTestWithId(testId + 1, name, grade, subject,"");
            List<QuestionPDFVO> vos = PDFParserUtil.parsePDF(is, offset);
            int index = 1;
            List<String> urls = new ArrayList<>();
            List<CreateImageVO> imageList = new ArrayList<>();
            for (QuestionPDFVO vo : vos) {
                try {
                    String key = new Date().getTime() +"_"+index+".png";
                    System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
                    AmazonS3 s3 = config.amazonS3();
                    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentType("image/png");
                    objectMetadata.setContentLength(vo.getImage().getLength());
                    urls.add(url + key);
                    s3.putObject(bucket, key, vo.getImage().getInputStream(), objectMetadata);
                    index++;
                    CreateImageVO createImageVO = new CreateImageVO();
                    createImageVO.setPosition(vo.getX1() + "," + vo.getY1() + "," + vo.getX2() + "," + vo.getY2());
                    createImageVO.setWidth(vo.getPageWidth());
                    createImageVO.setHeight(vo.getPageHeight());
                    createImageVO.setSortNum(vo.getQuestionNumber());
                    createImageVO.setPageNum(vo.getPageNumber());
                    createImageVO.setScore(vo.getScore());
                    createImageVO.setGrade(grade);
                    createImageVO.setSubject(subject);
                    createImageVO.setQuestionModel(vo.getQuestionModel());
                    createImageVO.setResultPosition(vo.getX3() + "," + vo.getY3() + "," + vo.getX4() + "," + vo.getY4());
                    createImageVO.setUrl(url + key);
                    imageList.add(createImageVO);
                } catch (AmazonServiceException e) {
                    System.err.println(e.getErrorMessage());
                    System.exit(1);
                }
            }

            allService.createImage(imageList, testId+1);
            return new CommonReturn(200, "上传成功！");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new CommonReturn(500, "上传失败！");
        }
        }
    @PostMapping("/crop-pdf-image")
    public ResponseEntity<byte[]> cropPdfImage(
            @RequestParam("file") MultipartFile pdfFile,
            @RequestParam int x1,
            @RequestParam int y1,
            @RequestParam int x2,
            @RequestParam int y2,
            @RequestParam int page) {

        try (PDDocument document = PDDocument.load(pdfFile.getInputStream())) {
            // 参数验证
            if (x1 < 0 || y1 < 0 || x2 <= x1 || y2 <= y1) {
                return ResponseEntity.badRequest().body("Invalid coordinates".getBytes());
            }

            // 验证页码有效性
            int totalPages = document.getNumberOfPages();
            if (page < 1 || page > totalPages) {
                return ResponseEntity.badRequest().body("Invalid page number".getBytes());
            }

            // 渲染PDF页面为图片
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage pageImage = renderer.renderImage(page - 1);  // PDF页码从0开始

            // 验证坐标范围
            if (x2 > pageImage.getWidth() || y2 > pageImage.getHeight()) {
                return ResponseEntity.badRequest().body("Coordinates exceed image dimensions".getBytes());
            }

            // 计算截取区域
            int width = x2 - x1;
            int height = y2 - y1;
            BufferedImage subImage = pageImage.getSubimage(x1, y1, width, height);

            // 转换图片为字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(subImage, "PNG", baos);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);

            return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Error processing PDF: " + e.getMessage()).getBytes());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        }
    }


}
